#include<bits/stdc++.h>

using namespace std;

//void init(vector<int> father)
//{
//	for (int i = 0; i < father.size(); i++)
//	{
//		father[i] = i;
//	}
//}
//
//int find(int u, vector<int> father)
//{
//	return u == father[u] ? u : father[u] = find(father[u], father);
//}
//
//bool isSame(int u,int v,vector<int> father)
//{
//	u = find(u, father);
//	v = find(v, father);
//
//	return u == v;
//}
//
//void join(int u, int v, vector<int> father)
//{
//	u = find(u, father);
//	v = find(v, father);
//
//	if (u == v) return;
//
//	father[v] = u;
//}

int main()
{

	int n, m;
	cin >> n >> m;

	vector<vector<int>> nums(n, vector<int>(m+1,0));

	for (int i = 0; i < n; i++)
	{
		int k;
		cin >> k;
		while (k--)
		{
			int a;
			cin >> a;
			nums[i][a]++;
		}
	}

	int q;
	cin >> q;
	while (q--)
	{
		int a, b;
		cin >> a >> b;
		int count = 0;
		for (int i = 0; i < n; i++)
		{
			if (nums[i][a] >= 1 && nums[i][b] >= 1)
			{
				count++;
			}
		}

		cout << count << endl;
	}
	return 0;
}